﻿



/*-------------------------------------------------------------------
 *  CommunicationBuddy                                              *
 *  Author: Slifty on thebuddyforum.com                             *
 *  Version: 0.5.9.4 BETA                                               *
 *  Credits: Special thanks goes to parrot <3                       *
 *  He allowed me to use his Plugin 'AlertMe' and modificate it!    *
 -------------------------------------------------------------------*/



using System.Linq;
using System.Windows.Forms;

namespace CommunicationBuddy
{
    using System;
    using System.Threading;
    using System.IO;
    using System.Text;
    using Styx.Common;
    using Styx.Helpers;
    using Styx.Pathing;
    using System.Threading;
    using System.Diagnostics;
    using Styx.WoWInternals;
    using Styx.WoWInternals.WoWObjects;
    using System.Text.RegularExpressions;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Runtime.InteropServices;
    using System.Xml.Linq;
    using System.Xml;
    using System.Net;
    using Styx.Plugins;
    using Styx.CommonBot;
    using Styx;
    using System.Media;
    using System.Globalization;


    public class CB : HBPlugin
    {

        public override string Name { get { return "CommunicationBuddy"; } }
        public override string Author { get { return "Slifty"; } }
        public override Version Version { get { return new Version(0, 5, 9, 4); } }
        public override bool WantButton { get { return true; } }
        public override string ButtonText { get { return "Settings"; } }

        private int whispCounter = 0;
        private bool newEntry = false; 
        private static readonly LocalPlayer Me = StyxWoW.Me;
        private bool init = false;


        public override void OnButtonPress()
        {

            CommunicationBuddy_Form cb_form = new CommunicationBuddy_Form();
            cb_form.ShowDialog();
        }

        private void BotStart(EventArgs args)
        {

            SXml.Load(false);

            Logging.Write("[{0}] Version {1} BETA", Name, Version);

            // Since version 0.5.8 we`ve new file name structure
            Deleting_old_files();
  
        }
        

        private string on_off(bool input)
        {

            if (input)

                return "on";
            else

                return "off";
        }


        public override void Initialize()
        {
            //For more information read comments at [....].Updater.cs
            //Updater.CheckAndStartSVN(); 
           
            if (!init)
            {

                init = true;
                BotEvents.OnBotStarted += BotStart;
                Lua.Events.AttachEvent("CHAT_MSG_WHISPER", handleWhispers);
                Lua.Events.AttachEvent("CHAT_MSG_BN_WHISPER", handleWhispers);
            }

            base.Initialize();

        }


        public override void Dispose()
        {
            //Logging.Write("[CommunicationBuddy] Disposing"); 
            
            if (Lua.Events != null)
            {

            //Logging.Write("[CommunicationBuddy] Detaching lua");

            Lua.Events.DetachEvent("CHAT_MSG_WHISPER", handleWhispers);
            Lua.Events.DetachEvent("CHAT_MSG_BN_WHISPER", handleWhispers);            
            }

            BotEvents.OnBotStarted -= BotStart;
            init = false;

            base.Dispose();
        }


        public override void Pulse()
        {

        }

        private void Deleting_old_files()
        {
            string[] files = { "Settings.cs", "WhisperLog.cs", "Settings_form.cs", "Settings_form.Designer.cs", "CommunicationBuddy.Xml.cs" };

            foreach (string file in files)
            {
                try
                {
                    if (File.Exists(string.Format(@"{0}\Plugins\CommunicationBuddy\{1}", Application.StartupPath, file)))
                    {

                        Logging.Write("[{0}] Try to delete {1}, because its outdated!", Name, file);
                        File.Delete(string.Format(@"{0}\Plugins\CommunicationBuddy\{1}", Application.StartupPath, file));
                    }
                }
                catch (ArgumentException eof1)
                {

                    Logging.Write("[{0}] Error {1}", Name, eof1);
                }
                catch (Exception eof2)
                {

                    Logging.Write("[{0}] Error {1}", Name, eof2);
                }
            }

            try
            {
                if(Directory.Exists(string.Format(Application.StartupPath + @"\Plugins\CommunicationBuddy\Media\")))
                {
                    
                    Directory.Delete(string.Format(Application.StartupPath + @"\Plugins\CommunicationBuddy\Media\", true));
                }
            }
            catch
            {

                Logging.Write("[{0}] Error while file deleting", Name);
            }
        }


        private void handleWhispers(object sender, LuaEventArgs args)
        {

            string author = args.Args[1].ToString();
            string message = args.Args[0].ToString();
            string answer = "";
            string alt_message = "";
            bool answer_alt = false;

            List<string> imc = new List<string>();
            List<string> wm = new List<string>();


            if (SXml.settings.whisperAlert)
            {

                AlertSnd();
            }

            if (SXml.settings.answering)
            {
                try
                {
                    var xmlroot = XElement.Load(string.Format(@"{0}\Plugins\CommunicationBuddy\Wordlists\{1}", Application.StartupPath, SXml.settings.wordlist));

                    var option1 = from imc_temp in xmlroot.Descendants("IfMessageContains")
                                  select imc_temp.Value;

                    var option2 = from wm_temp in xmlroot.Descendants("WhisperMessage")
                                  select wm_temp.Value;

                    var option3 = from alt_message_temp in xmlroot.Descendants("Alternative")
                                  select alt_message_temp.Value;


                    foreach (var imc_temp in option1)
                    {

                        imc.Add(imc_temp);
                    }

                    foreach (var wm_temp in option2)
                    {

                        wm.Add(wm_temp);
                    }

                    foreach (var alt_message_temp in option3)
                    {

                        alt_message = alt_message_temp;
                    }
                }
                catch
                {

                    Logging.Write("[{0}] Unable to load {}", Name, SXml.settings.wordlist);
                }
                //End try

                answer = Get_Answer(message, imc, wm);

                if (string.IsNullOrEmpty(answer))
                {

                    Logging.Write("Empty or Null");
                    Logging.Write(alt_message);
                    answer = alt_message;
                    answer_alt = true;
                }

                Do_LoggingSnd(author, message, answer, answer_alt);

            }
            else
            {

                Do_LoggingSnd(author, message, "", false);
            }
        }


        private string Get_Answer(string message, List<string> message_s, List<string> answer_s)
        {

            //message   => Private message
            //message_s => Message sheet
            //answer_s  => Answer sheet

            string anw = "";
            CultureInfo c = CultureInfo.CurrentCulture;
            Random rnd = new Random();


            for (int i = 0; i < message_s.Count; i++)
            {

                string ms_temp = message_s[i].ToLower(c);

                if (ms_temp.Contains(message.ToLower(c)))
                {

                    if (answer_s[i].Contains('|'))
                    {

                        string[] temp = answer_s[i].Split('|');
                        int rn = rnd.Next(0, temp.Count());
                        anw = temp[rn];

                        break;
                    }
                    else
                    {

                        anw = answer_s[i];

                        break;
                    }
                }
            }

            return anw;
        }


        private void Do_LoggingSnd(string author, string message, string answer, bool alternative)
        {

            // author      => Author
            // message     => Private message
            // answer      => Answer 
            // alternative => Bool if answer is from alternative

            if (!newEntry)
            {

                PluginLog.newEntry();
                newEntry = true;
            }


            Logging.Write("[{0}] Received whisper", Name);
            PluginLog.writeLine(string.Format("{0}: {1}", author, message));

            if (SXml.settings.answering)
            {

                if (!string.IsNullOrEmpty(answer))
                {

                    if (!alternative)
                    {

                        Logging.Write("[{0}] Message sent", Name);
                    }
                    else
                    {

                        Logging.Write("[{0}] Alternative message sent", Name);
                    }

                    DoDelay(SXml.settings.delayV1, SXml.settings.delayV2);

                    Lua.DoString(string.Format("SendChatMessage('{0}', 'WHISPER', 'nil', '{1}')", answer, author));
                    PluginLog.writeLine(string.Format("{0} (Me): {1}", Me.Name, answer));
                }
                else
                {

                    Logging.Write("[{0}] No message sent, because no alternative answer is given", Name);
                    PluginLog.writeLine(string.Format("No alternative answer found for '{0}'", message));
                }

            }
        }


        private void AlertSnd()
        {
            try
            {

                SoundPlayer sp = new SoundPlayer();
                sp.SoundLocation = Application.StartupPath + @"\Plugins\CommunicationBuddy\Misc\beep.wav";
                sp.Play();
            }
            catch
            {

                Logging.Write("{0} Error: Could not play audio.", Name); 
            }
        }


        private void DoDelay(int v1, int v2)
        {

            if (SXml.settings.delay)
            {

                Random rnd = new Random();

                Thread.Sleep(rnd.Next(v1, v2));
            }
        }
    }
}